import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  NavBar,
  NoticeBar,
  Button,
  Card,
  List,
  Checkbox,
  Dialog,
  Modal,
  Form,
  Input,
  Toast,
} from "antd-mobile";
import { useSelector, useDispatch } from "react-redux";
import {
  stateChange,
  delPer,
  addPer,
  editPer,
} from "../../store/TickPersonSlice";
import { EditSOutline, DeleteOutline } from "antd-mobile-icons";
import http from "../../utils/http";
import styles from "./index.module.css";

const Index = () => {
  const navigate = useNavigate();
  //获取仓库数据
  const { tickPersonList } = useSelector((state) => state.TickPersonSlice);
  const dispatch = useDispatch();

  //定义组件状态
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false); //控制弹框显示隐藏
  //true 表示添加操作  false 表示编辑操作
  const [disState, setDisState] = useState(false);

  //删除乘车人
  const handelDel = async (item) => {
    const result = await Dialog.confirm({
      content: "您确定删除当前乘车人吗？",
    });
    if (result) {
      dispatch(delPer(item));
    } else {
      console.log("取消删除");
    }
  };

  //添加乘车人
  const handelAddPer = () => {
    setVisible(true); //显示弹框
    setDisState(true); //表示添加操作
    //清空数据
    form.resetFields();
  };

  //修改乘车人
  const handelEditPer = (item) => {
    setVisible(true); //显示弹框
    setDisState(false); //表示编辑操作
    //数据回填
    form.setFieldsValue(item);
  };

  //表单提交
  const onFinish = () => {
    //判断是添加还是修改：disState true 添加 false 修改
    if (disState) {
      //设置添加乘车人数据
      const addObj = { ...form.getFieldsValue(), id: Date.now(), state: false };
      dispatch(addPer(addObj));
    } else {
      const editObj = form.getFieldsValue(true);
      dispatch(editPer(editObj));
    }

    setVisible(false); //隐藏弹框
    form.resetFields();
  };

  //上传证件识别信息
  const handelUpFileId = () => {
    //1.点击btn按钮，能够访问本地的图片
    const inputEl = document.createElement("input");
    inputEl.type = "file"; //为什么这样写？因为input的file属性能够访问本地
    inputEl.click(); //让input元素触发click事件

    //触发input的change事件，读取文件内容
    inputEl.onchange = async () => {
      //获取到文件对象
      const file = inputEl.files[0];

      //创建一个FormData对象，并把文件添加到里面
      const fileData = new FormData();
      fileData.append("file", file);

      //发送请求
      const res = await http.post("/api/orc/upload/image", fileData);
      const { code, data, message } = res.data;
      if (code === 200) {
        Toast.show({
          content: message,
          icon: "success",
        });
        //将识别到的信息显示到表单中
        form.setFieldsValue(data);
      } else {
        Toast.show({
          content: message,
          icon: "fail",
        });
      }
    };
  };

  return (
    <div>
      <NavBar onBack={() => navigate(-1)}>选择乘车人</NavBar>
      <NoticeBar
        content="不满6岁儿童可申报免费乘车，申报免费儿童票流程"
        color="alert"
      />
      <div className={styles.per_wrap}>
        <Button color="primary" size="mini" onClick={() => handelAddPer()}>
          点击按钮添加乘车人
        </Button>
        <Card title="乘车人列表：">
          <List>
            {tickPersonList.map((item, ind) => (
              <List.Item
                key={ind}
                description={item.code}
                prefix={
                  <EditSOutline
                    fontSize={20}
                    color="blue"
                    onClick={() => handelEditPer(item)}
                  />
                }
                extra={
                  <div>
                    <DeleteOutline
                      fontSize={20}
                      color="red"
                      style={{ marginRight: 20 }}
                      onClick={() => handelDel(item)}
                    />
                    <Checkbox
                      checked={item.state}
                      onChange={() => {
                        dispatch(stateChange(item));
                        navigate(-1);
                      }}
                    />
                  </div>
                }
              >
                {item.name}
              </List.Item>
            ))}
          </List>
        </Card>
      </div>

      {/* 创建弹框，1.添加 2.修改 以上两个功能都要使用同一个弹框 */}
      <Modal
        visible={visible}
        content={
          <Form
            form={form}
            onFinish={onFinish}
            layout="horizontal"
            footer={
              <Button block type="submit" color="primary" size="large">
                提交
              </Button>
            }
          >
            <Form.Header>{disState ? "添加" : "编辑"}</Form.Header>
            {disState && (
              <div className={styles.add_wrap}>
                <Button size="mini" onClick={() => handelUpFileId()}>
                  上传证件录入信息
                </Button>
              </div>
            )}
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: "姓名不能为空" }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
            <Form.Item
              name="code"
              label="身份证"
              rules={[{ required: true, message: "证件不能为空" }]}
            >
              <Input placeholder="请输入证件" />
            </Form.Item>
          </Form>
        }
        closeOnAction
        onClose={() => {
          setVisible(false);
        }}
        showCloseButton={true}
      />
    </div>
  );
};

export default Index;
